'''This file provides a few extended graphic functions, such as pattern filling,
or complex random graphic generation.'''

from pygame import surface, rect, image

blit_window_list = {}

def pattern_fill(pattern, target, target_rect=None):
    '''Fills the target surface with the intended pattern. Optionally, you may
    restrict the area covered by pattern_fill by passing target_rect as argument.'''

    #Set the clipping area to avoid overshooting the target area
    clip = target.get_clip()
    if not target_rect:
        target_rect = target.get_rect()
    target.set_clip(target_rect)

    #Fill the area
    pattern_rect = pattern.get_rect()
    for x in xrange(target_rect.x, target_rect.x+target_rect.w, pattern_rect.w):
        for y in xrange(target_rect.y, target_rect.y+target_rect.h, pattern_rect.h):
            target.blit(pattern, (x,y))

    #Restore the original clipping area
    target.set_clip(clip)

def blit_through_window(source_img, source_area, dest_img, dest_area, window, window_area, alpha=None):
    '''Performs the blitting of a source surface onto a destination surface
    through a window that limits the portion of the image to be pasted in a
    non-rectangular shape.'''
    #Criar trecho a ser colado:
    piece = surface.Surface(window_area.size).convert()
    #Copiar pedaco do fundo destruido
    piece.blit(source_img, (0, 0), source_area)
    #Recortar area no formato do buraco
    piece.blit(window, (0, 0), window_area)
    #Atualizar a transparencia
    piece.set_colorkey((255,0,255))
    #Verificar se htem intencao de setar alpha
    if alpha:
        piece.set_alpha(alpha)
    #Colar pedaco recortado na imagem do mapa
    dest_img.blit(piece, dest_area)

def load_blit_window(file_name):
    '''Loads and returns a blit window from a file. This function keeps track of
    previously loaded blit windows to avoid multiple instances of the exact same
    image.'''
    global blit_window_list
    if not blit_window_list.has_key(file_name):
        blit_window_list[file_name] = image.load(file_name).convert()
    blit_window_list[file_name].set_colorkey((0,0,0))
    print blit_window_list[file_name]
    return blit_window_list[file_name]

